package cn.cinz.cyxx.controller;

import cn.cinz.cyxx.common.ResultJson;
import cn.cinz.cyxx.model.User;
import cn.cinz.cyxx.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 用户控制器
 *
 * @Author: zengcheng
 * @Description: 用户信息处理
 * @Date: 2021/9/6 22:54
 */
@Controller
@CrossOrigin
@RequestMapping("/user")
public class UserController {

    /**
     * 日志
     */
    private Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;


    /**
     * 获得用户信息
     * @param session
     * @param user
     * @return
     */
    @RequestMapping(value = "/getUserInfo", method = RequestMethod.POST)
    public @ResponseBody ResultJson getUserInfo(HttpSession session,User user){

        try {
            user = (User) session.getAttribute("user");
            User userInfo = userService.getUserinfo(user.getId());
            return ResultJson.ok().data(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultJson.error().message(e.getMessage());
        }

    }

    /**
     * 修改用户信息
     * @return
     */
    @RequestMapping("/editUserInfo")
    public @ResponseBody ResultJson editUserInfo(User user){
        try {
            userService.editUserInfo(user);
            return ResultJson.ok();
        } catch (Exception e) {
            return ResultJson.error().message(e.getMessage());
        }
    }


    /**
     * Session回收 并重定向到登陆页
     * @param session
     * @return
     */
    @RequestMapping(value = "/removeSession", method = RequestMethod.GET)
    public String removeSession(HttpSession session){
        session.removeAttribute("user");
        return "redirect:/login";
    }


}
